<template>
  <div>
    <div
      v-if="empty"
      class="empty justify-center-center"
      @click="handleOpenCamera"
    >
      <img src="@/assets/main/photo.png" alt="" class="empty-img" />
    </div>
    <div v-else @click="handleOpenCamera" class="empty">
      <Loading
        type="spinner"
        v-if="urlLoading"
        color="#0094ff"
        class="absolute top-1/2 left-1/2"
      />
      <img :src="urlImg" alt="" class="h-full w-full object-cover" />
    </div>
    <input
      ref="upload"
      type="file"
      accept="image/*"
      capture="camera"
      style="display: none"
    />
  </div>
</template>

<script>
import { getImgToBase64, ossUpload } from '@/common/ossUpload'
import { getLivenessToken } from '@/api'
import { setLocalStore } from '@/config/global'
import { Loading } from 'vant'
export default {
  name: 'UploadImage',
  components: { Loading },
  data() {
    return {
      empty: true,
      urlLoading: false,
      urlImg: ''
    }
  },
  created() {},
  mounted() {},
  methods: {
    handleOpenCamera() {
      this.uploadImg().then(file => {
        // 安卓app会拦截返回的file的type为空
        // if (file.type.indexOf('image') === 0) {
        //   this.$toast.fail('图片搞丢了，请联系管理员')
        //   this.$refs.upload.value = null // 上传成功清理
        //   return
        // }
        this.empty = false
        this.urlImg = URL.createObjectURL(file)
        this.urlLoading = true
        getImgToBase64(file, base64 => {
          getLivenessToken({
            returnUrl: `${window.location.origin}/creditPhoto?hasScore=true`,
            ktpBase64: base64
          })
            .then(res => {
              window.location.href = `https://liveness.advance.ai/h5/index?biz_token=${res}`
              setLocalStore('advanceToken', res, true)
            })
            .catch(() => {
              this.$toast.fail('失败了,请重试')
              this.urlLoading = false
            })
        })
        ossUpload(file)
      })
    },
    uploadImg() {
      return new Promise((resolve, reject) => {
        this.$refs.upload.dispatchEvent(new MouseEvent('click'))
        this.$refs.upload.onchange = event => {
          if (!event) {
            reject('empty')
          }
          resolve(event.target.files[0])
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.empty {
  height: 177px;
  background: #ffffff;
  border-radius: 6px;
}
.empty-img {
  width: 54px;
  height: 54px;
}
</style>
